<?php

namespace app\widgets;

use Yii;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

/**
 * 列表排序链接
 * Class SortColumnLink
 * @package app\widgets
 *
 * 使用方法：
 * ```
 * echo SortColumnLink::widget(['txt' => '刷新时间', 'name' => 'refresh_time']);
 * ```
 */
class SortColumnLink extends Widget
{
    /**
     * @var string 链接内容
     */
    public $txt = '';
    /**
     * @var string 排序列名
     */
    public $name = '';
    /**
     * @var boolean 是否显示指示图标
     */
    public $withArrow = true;

    /**
     * @inheritdoc
     */
    public function run()
    {
        $nextOrder = 'DESC';
        if (empty($this->order)) {
            $currentOrder = Yii::$app->request->get('sort_order');
            $orderMap = ['ASC' => 'DESC', 'DESC' => 'ASC'];
            if (isset($orderMap[$currentOrder])) {
                $nextOrder = $orderMap[$currentOrder];
            }
        }
        $arrow = '';
        if ($this->withArrow && !empty($currentOrder) && Yii::$app->request->get('sort_name') == $this->name) {
            $arrow = '<i class="fa fa-long-arrow-' . ['ASC' => 'up', 'DESC' => 'down'][$currentOrder] . '"></i>';
        }
        echo Html::a(Html::encode($this->txt) . $arrow, Url::current(['sort_name' => $this->name, 'sort_order' => $nextOrder]));
    }
}
